﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.IO;

using Azure.Resources;
using Azure.Logger;

namespace Azure.Configuration
{
    internal static class AzConfigValidator
    {
        private static Assembly s_assembly = null;
        private static XmlReaderSettings s_xsd = null;

        //验证配置文件，如果失败则退出程序
        internal static void Validate(XmlReader xml)
        {
            if (s_assembly == null)
            {
                try
                {
                    Assembly assembly = Assembly.Load("Azure.Resources");
                }
                catch (Exception ex)
                {
                    AzLogger.Error("加载Azure.Resources程序集失败进程将结束运行, 请检查程序集的位置", ex);
                    Environment.Exit(0);
                }
            }

            if (s_xsd == null)
            {
                s_xsd = new XmlReaderSettings();
                s_xsd.ValidationType = ValidationType.Schema;
                s_xsd.ValidationEventHandler += XsdValidationEventHandler;
                s_xsd.Schemas.Add(null, XmlReader.Create(AzEmbeddedResourcesManager.GetRobotConfigSchemaResource()));
            }

            XmlReader reader = null;
            try
            {
                reader = XmlReader.Create(xml, s_xsd);

                //验证整个文档
                while (reader.Read())
                {
                }

            }
            catch (Exception e)
            {
                AzLogger.Error("创建XmlReader时发生了错误", e);
                Environment.Exit(0);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }

        private static void XsdValidationEventHandler(Object sender, ValidationEventArgs arg)
        {
            switch (arg.Severity)
            {
                case XmlSeverityType.Error:
                    AzLogger.Error("验证配置文件格式时出现错误，具体错误如下：", arg.Exception);
                    Environment.Exit(0);
                    break;

                case XmlSeverityType.Warning:
                    AzLogger.Warn("验证配置文件格式时出现警告，具体信息如下：" + arg.Message);
                    break;
            }
        }
    }
}
